# -*- coding: utf-8 -*-
from django.forms.forms import BoundField
from django.forms.fields import DateTimeField, DateField, TimeField
from django.forms.widgets import TextInput, CheckboxInput, CheckboxSelectMultiple, RadioSelect, Textarea, DateInput, \
    TimeInput, DateTimeInput, NumberInput
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django import template
import json

register = template.Library()

@register.filter
def input_type(field):
    """
    返回一个field的表单类型
    """
    try:
        widget = field.field.widget
    except:
        raise ValueError("Expected a Field, got a %s" % type(field))

    if isinstance(widget, TextInput):
        return u'text'
    if isinstance(widget, CheckboxInput):
        return u'checkbox'
    if isinstance(widget, CheckboxSelectMultiple):
        return u'multicheckbox'
    if isinstance(widget, RadioSelect):
        return u'radioset'
    if isinstance(widget, Textarea):
        return u'textarea'

    return u'default'

@register.filter(name='add_css_class')
def add_css_class(value, arg):
    """
    动态给widget指定属性
    """
    attrs = {
        'placeholder': value.label
    }
    arg = arg.split('&')
    add_class = arg[0]
    if len(arg) > 1:
        other_dict = eval(arg[1])
        for key,val in other_dict.items():
            attrs.update({
                key: val
            })
    if hasattr(value.field, 'max_length'):
        attrs.update({
            'maxlength': value.field.max_length
            })
    if add_class:
        attrs.update({
            'class': add_class
            })
    if value.field.required:
        attrs.update({
            'required': 'required'
            })

    return value.as_widget(attrs=attrs)


@register.filter(name='add_placeholder')
def add_placeholder(value):
    attrs = {
        'placeholder': u'请输入'+value.label
    }

    return value.as_widget(attrs=attrs)